import { IGlobalControl } from '@/pages/Analysis/Board/components/Filters/types';
import { IFilter, IModel } from '@/pages/SelfQuery/type';
import { DATA_ACTION_TYPE, FILTER_OPERATOR, OperatorFilterTypes, VISUALTYPES } from '@/pages/SelfQuery/constants';
import { isLevelVisualType } from '@/pages/SelfQuery/utils';

export const getDashboardWidgetFilters = (formValue: any, controls: IGlobalControl[]) => (viewId?: number, model?: any, widgetId?: any) => {
  if(!viewId && !model && !widgetId){
    return formValue
  }
  //看板全局过滤添加
  let filters: IFilter[] = [];
  if (controls && controls.length) {
    for (let i = 0; i < controls.length; i++) {
      let options = controls[i];
      const { key } = options;
      let value = formValue[key];
      if (!value || JSON.stringify(value).indexOf('*') !== -1 || !value.length) {
        continue;
      }
      if (options && options.relatedViews) {
        let { relatedViews, relatedItems, operator,dateFormat } = options;
        if (!operator) {
          operator = OperatorFilterTypes.Equal;
        }
        if (Array.isArray(value)) {
          operator = OperatorFilterTypes.In;
        }
        const relatedWidgets = !relatedItems ? [] : Object.keys(relatedItems).filter((v:any)=>relatedItems[v].checked)
        const viewKeys = Object.keys(relatedViews);
        if (viewKeys && viewKeys.includes(String(viewId)) && relatedWidgets && relatedWidgets.includes(String(widgetId))) {
          const { name } = relatedViews[viewId];
          const modelVal: IModel = model[name];
          let visualType = VISUALTYPES.String;
          if (modelVal) {
            visualType = modelVal.visualType;
            if (isLevelVisualType(visualType)) {
              operator = OperatorFilterTypes.Regexp;
              if (value && Array.isArray(value)) {
                value = value.join('|');
              }
            } else if (visualType === VISUALTYPES.Date && Array.isArray(value)) {
              operator = FILTER_OPERATOR.BETWEEN;
              value = value.map(v=>`'${v.format(dateFormat)}'`)
            }
          }

          const filter: IFilter = {
            name,
            operator,
            type: 'filter',
            value,
            sqlType: 'STRING',
            action: DATA_ACTION_TYPE.filter,
            visualType,
          };
          if (visualType === VISUALTYPES.Date) {
            filter.column = `cast(${name} as TIMESTAMP)`;
          }
          filters.push(filter);
        }
      }
    }
  }
  return filters;
};
